package com.kfm.servlet.day03;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/down")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        File file = new File("D:\\temp\\upload\\" + name);

        String mimeType = getServletContext().getMimeType(file.getName());
        // text/plain text/html text/css text/javascript image/png image/jpeg image/gif application/pdf
//        System.out.println(mimeType);
        // 设置响应头
        resp.setContentType(mimeType);
        resp.setHeader("Content-Disposition", "attachment;filename=" + file.getName());

        // 响应体
        FileInputStream fis = new FileInputStream(file);
        fis.transferTo(resp.getOutputStream());
        fis.close();
    }
}
